#coding=utf8
from utils.jsonUtils import load_str

from ws_setting import core_logger

class WebSocketRequest:
    def __init__(self, session):
        self.application = session.app_container.ws_application

        self._session = session

    def app(self, key, value=None, default=None, append=False):
        """
            处理整个应用范围的变量
            当没有提供value值时候，则需要返回key对应数据
            当同时提供key和value，则将key所对应的值修改为新的value
            不提供key，则抛出KeyError异常
            
            default 只在key所对应的值不存在的情况下，才会使用default为key赋值
        """
        if value and default:
            raise ValueError("default 和 value 不能同时存在")

        if key:
            if not value == None:
                self.application[key] = value
                core_logger.debug("a new attr '%s' had been added to application scope " % key)
            else:
                if key not in self.application and default is not None:
                    self.application[key] = default
                return self.application.get(key, None)
        else:
            raise KeyError("At least provide a key")

    def app_exist(self, key):
        return key in self.application

    def attr(self, name, default=None):
        return self._session.__dict__.get(name, default)


    def param(self, name, default=None):
        """
            获取建立连接时候的参数
        """
        return self._session.parameters.get(name, default)

    def get_data(self, key=None):
        if self._session.data:
            _data = self._session.data
            if type(_data) == list:
                return map(lambda l: load_str(l.decode()).get(key, None), _data)
            else:
                _data = load_str(self._session.data.decode())
                if key :
                    return _data.get(key, None)
                return _data
        else:
            return ""


